package Survey;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;


public class SurveyCreatorGui extends JFrame {
	
	private static final long serialVersionUID = 1958774088948790153L;
	
	public static final int WIDTH = 1000;
	public static final Dimension TOPSIZE = new Dimension(WIDTH - 20,35);
	
	SurveyCreator control;
	Vector<SurveyParameters> surveys;
	Vector<String> location;
	Vector<Boolean> visible;
	int index = 0;
	
	JPanel container;
	JScrollPane scrollPanel;
	JComboBox where;
	
	public SurveyCreatorGui(Vector<SurveyParameters> surveys, SurveyCreator control){
		
		this.surveys = surveys;
		this.control = control;
		visible = new Vector<Boolean>();
		
		for(SurveyParameters sp : surveys){
			visible.add(new Boolean(true));
			index++;
		}
		
		//the panel that contains everything
		JPanel mainPanel = new JPanel();
		add(mainPanel);
		mainPanel.setLayout(new BorderLayout());
		mainPanel.setBorder(BorderFactory.createLineBorder(Color.blue, 2));

		//creates header top within MainPanel
		JPanel TopPanel = new JPanel();
		TopPanel.setLayout(new BoxLayout( TopPanel, BoxLayout.Y_AXIS));
		JPanel header1 = new JPanel();
		JLabel header1L = new JLabel("University of California San Diego, Economics Department");
		header1.add(header1L);
		header1.setBackground(new Color(100, 149, 237));
		header1.setOpaque(true);
		JPanel header2 = new JPanel();
		JLabel header2L = new JLabel("Survey Creator");
		header2.add(header2L);
		header2.setBackground(new Color(255,215,0));
		header2.setOpaque(true);        
		header1.setAlignmentX(Component.CENTER_ALIGNMENT);
		header2.setAlignmentX(Component.CENTER_ALIGNMENT);
		TopPanel.add(header1);
		TopPanel.add(header2);
		
		//centerPanel within mainPanel
		
		//scrollPanel within centerPanel
		JPanel CenterPanel = new JPanel();
		container = new JPanel();
		scrollPanel  = new JScrollPane(container);
		container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
		scrollPanel.setPreferredSize(new Dimension(WIDTH + 20,600));
				
		CenterPanel.add(scrollPanel);
		CenterPanel.setBackground(Color.white);
		CenterPanel.setOpaque(true);

		
		
		//bottom
		JPanel BottomPanel = new JPanel();
		BottomPanel.setLayout(new BoxLayout(BottomPanel, BoxLayout.X_AXIS));
		BottomPanel.setBackground(Color.white);
		BottomPanel.setOpaque(true);
		
		JComboBox chooseType = new JComboBox(new String[]{"Open-Ended", "Multiple Choice"});
		chooseType.setPreferredSize(new Dimension(150,20));
		chooseType.setMaximumSize(new Dimension(150,50));
		
		//where does the new module go?
		location = new Vector<String>();
		location.add("End");
		where = new JComboBox(location);
		where.setPreferredSize(new Dimension(100, 15));
		where.setMaximumSize(new Dimension(100, 20));
		
		JButton addQuestion = new JButton("Add");
		addQuestion.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				SurveyCreatorGui gui = (SurveyCreatorGui)((JButton)e.getSource()).getTopLevelAncestor();
				
				String type = (String)((JComboBox)((JButton)e.getSource()).getParent().getComponent(1)).getSelectedItem();
				gui.location.add("" + ++gui.index);
				gui.visible.add(new Boolean(true));
				CreatorModule temp;
				if(type.equals("Open-Ended")){
					gui.surveys.add(new SurveyParameters(gui.index,"", null, null, SurveyParameters.OPEN_ENDED, new int[1], false));
					temp = new CModuleText(gui.surveys.get(gui.index-1), gui.visible);
					
				}else{
					gui.surveys.add(new SurveyParameters(gui.index,"", null, null, SurveyParameters.SINGLE_CHOICE, null, false));
					temp = new CModuleMultipleChoice(gui.surveys.get(gui.index-1), gui.visible);
				}
				gui.container.add(temp);
				if(gui.where.getSelectedIndex() != 0){
					temp.data.index = Integer.parseInt((String)gui.where.getSelectedItem());
					gui.updateList();
				}
				
				gui.container.validate();
				gui.scrollPanel.validate();

			}
		});
		
		JButton updateOrder = new JButton("Update List");
		updateOrder.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				((SurveyCreatorGui)((JButton)e.getSource()).getTopLevelAncestor()).updateList();
			}
		});
		
		JButton save = new JButton("Save");
		save.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				SurveyCreatorGui scg = ((SurveyCreatorGui)((JButton)e.getSource()).getTopLevelAncestor());
				scg.updateList();
				SurveyParameters working;
				int message = 0;
				boolean errors = false;
				
				for(int i = 0; i < scg.surveys.size(); i++){
					working = scg.surveys.get(i);
					message = 0;
					if(working.question == null || working.question.equals("")){
						message += 1;
					}
					if(working.type == SurveyParameters.OPEN_ENDED){
						if(working.dimensions[0] == 0){
							message += 2;
						}
					}else{
						int count = 0;
						for(String[] sa : working.options){
							for(String s : sa){
								if(s == null || s.equals("")){
									message += 2;
									break;
								}
								if(s.startsWith("xx") && ++count >= 2){
									message += 2;
									break;
								}
							}
							if(message >= 2){
								break;
							}
						}
					}
					if(message != 0){
						errors = true;
						((CreatorModule)scg.container.getComponent(i)).highlight(message);
					}	
				}
				
				if(!errors){
					scg.control.saveData();
				}
			}
		});
		
		BottomPanel.add(Box.createHorizontalGlue());
		BottomPanel.add(chooseType);
		BottomPanel.add(new JLabel(" at Location: "));
		BottomPanel.add(where);
		BottomPanel.add(Box.createHorizontalGlue());
		BottomPanel.add(addQuestion);
		BottomPanel.add(updateOrder);
		BottomPanel.add(save);
		BottomPanel.add(Box.createHorizontalGlue());
		
		
		mainPanel.add(TopPanel, BorderLayout.NORTH);
		mainPanel.add(CenterPanel, BorderLayout.CENTER);
		mainPanel.add(BottomPanel, BorderLayout.SOUTH);

		setSize(new Dimension(1200, 800));
		setVisible(true);
	}
	
	
	//updates list if size of a component changes
	public void updateSize(){
		
		container.removeAll();
		for(int i = 0; i < surveys.size(); i++){
			surveys.get(i).index = i + 1;
			if(surveys.get(i).type == SurveyParameters.OPEN_ENDED){
				CModuleText temp = new CModuleText(surveys.get(i), visible);
				container.add(temp);
			}else{
				CModuleMultipleChoice temp = new CModuleMultipleChoice(surveys.get(i), visible);
				container.add(temp);
			}
		}
		
		container.validate();
		container.repaint();
		
	}
	
	//updates the order of the list
	public void updateList(){
		
		//go through and see which modules change position
		int count = 0;
		for(int  i = 0; i < surveys.size(); i++){
			if(surveys.get(i).index != i+1){
				count++;
			}
		}
		
		if(count == 0){
			return;
		}
		
		int[] oldPositions = new int[count];
		SurveyParameters[] movedQuestions= new SurveyParameters[count];
		int index = 0;
		
		for(int  i = 0; i < surveys.size(); i++){
			if(surveys.get(i).index != i+1){
				oldPositions[index] = i;
				movedQuestions[index] = surveys.get(i);
				index++;
			}
		}
		
		//remove them from the vector
		for(int i = count; i > 0; i--){
			surveys.remove(oldPositions[i - 1]);
		}
		
		//sort them according to where they go
		quicksortList(oldPositions, movedQuestions, 0, count-1);
		
		
		//add them back in
		for(int i = 0; i < count; i++){
			if(movedQuestions[i].index - 1 > surveys.size()){
				movedQuestions[i].index = surveys.size() + 1;
			}
			surveys.add(movedQuestions[i].index - 1, movedQuestions[i]);
		}
		
		
		//redraw the display
		updateSize();

		
		container.validate();
		
	}
	
	private void quicksortList(int[] oldPositions, SurveyParameters[] movedQuestions, int start, int end){
		
	    if (start > end){
	        return;
	    }
	    int pivot = partition(oldPositions, movedQuestions, start, end);
	    quicksortList(oldPositions,movedQuestions, start, pivot - 1);
	    quicksortList(oldPositions,movedQuestions, pivot + 1, end);
		
		
	}
	
	private int partition(int[] oldPositions, SurveyParameters[] movedQuestions, int start, int end){
		//places pivot at end and index at beginning
		SurveyParameters pivot = movedQuestions[end];
	    int border = start;
	    
	    //goes through items 
	    //if they need to be swapped it does so and 
	    //moves the index to reflect that change
	    for (int i = start; i < end; i++) {
	    	if (movedQuestions[i].index < pivot.index) {
	    		swap(movedQuestions, border, i);
	    		swap(oldPositions, border++, i);
	    	}
	    }
	    
	    //places the pivot where it should be
	    swap(movedQuestions, border, end);
	    swap(oldPositions, border, end);
	    
	    //returns the location of the pivot
	    return (border);
	  }
	  
	  //swaps members of an array of SurveyParameters
	  private static void swap(SurveyParameters a[], int i, int j){
		  SurveyParameters temp = a[i];
		  a[i] = a[j];
		  a[j] = temp;
	  }
	  
	  private static void swap(int a[], int i, int j){
		  int temp = a[i];
		  a[i] = a[j];
		  a[j] = temp;
	  }

	
}
